<template>
  <el-dialog
    top="2vh"
    title="考前汇总"
    v-model="dialogVisible"
    width="80%"
    :before-close="handleClose"
    class="exam-summary-dialog"
  >
    <el-container style="height: 70vh; border: 1px solid #eee">
      <el-container>
        <el-main class="right">
          <el-col>
            <el-card class="qu_list">
              <div>
                <!-- 空数据提示 -->
                <el-empty
                  v-if="!safeRecordData.length"
                  description="暂无答题数据"
                >
                  <template #description>
                    <p>暂无答题数据，您可以选择继续答题或直接交卷</p>
                  </template>
                  <el-button type="primary" @click="onConfirm"
                    >确认交卷</el-button
                  >
                </el-empty>

                <!-- 客观题部分 -->
                <template
                  v-for="(item, index) in safeRecordData"
                  :key="'obj-' + index"
                >
                  <div
                    v-if="
                      item &&
                      (item.quType === 1 ||
                        item.quType === 2 ||
                        item.quType === 3)
                    "
                    :class="['question-item', 'index' + index]"
                  >
                    <el-row :gutter="24">
                      <el-col :span="20" style="text-align: left">
                        <!-- 题干区域 -->
                        <div class="question-title">
                          <div class="qu_content">
                            <span class="qu_num">{{ index + 1 }}. </span
                            >{{ item.title }}
                          </div>
                          <div v-if="item.image != null && item.image != ''">
                            <el-image
                              :src="item.image"
                              style="max-width: 200px"
                            />
                          </div>
                        </div>

                        <!-- 选项区域 -->
                        <el-radio-group class="qu_choose_group">
                          <el-radio
                            v-for="(option, optionIndex) in item.option"
                            :key="'option-' + optionIndex"
                            :label="option.content"
                            border
                            class="qu_choose"
                            :class="{
                              current:
                                item.myOption != null &&
                                isCheck(item.myOption, option.sort),
                              imgC: option.image != null && option.image != '',
                            }"
                          >
                            <span class="option-letter">{{
                              numberToLetter(optionIndex)
                            }}</span>
                            <span class="option-content">{{
                              option.content
                            }}</span>
                            <div
                              v-if="option.image != null && option.image != ''"
                            >
                              <el-image
                                :src="option.image"
                                style="max-width: 200px"
                                class="qu_choose_tag_img"
                              />
                            </div>
                          </el-radio>
                        </el-radio-group>

                        <!-- 我的答案区域 -->
                        <div class="qu_analysis">
                          <el-card class="my-answer-card">
                            <div>
                              <span class="answer-label">我的答案：</span>
                              <span
                                :class="[
                                  'answer-value',
                                  getAnswerClass(item.isRight),
                                ]"
                              >
                                {{ formatUserAnswer(item) }}
                              </span>
                            </div>
                          </el-card>
                        </div>
                      </el-col>
                    </el-row>
                    <el-divider />
                  </div>
                </template>

                <!-- 主观题部分 -->
                <template
                  v-for="(item, index) in safeRecordData"
                  :key="'subj-' + index"
                >
                  <div
                    v-if="item && item.quType === 4"
                    :class="['question-item', 'index' + index]"
                  >
                    <el-row :gutter="24">
                      <el-col :span="20" style="text-align: left">
                        <!-- 题干部分 -->
                        <div class="question-title">
                          <div class="qu_content">
                            <span class="qu_num">{{ index + 1 }}. </span
                            >{{ item.title }}
                          </div>
                          <div v-if="item.image != null && item.image != ''">
                            <el-image
                              :src="item.image"
                              style="max-width: 200px"
                            />
                          </div>
                        </div>

                        <!-- 简答题内容区域 -->
                        <div class="qu_analysis">
                          <el-card class="my-answer-card">
                            <div>
                              <span class="answer-label">我的答案：</span>
                              <span
                                :class="[
                                  'answer-value',
                                  getAnswerClass(item.isRight),
                                ]"
                              >
                                {{ item.myOption || '未作答' }}
                              </span>
                            </div>
                          </el-card>
                        </div>
                      </el-col>
                    </el-row>
                    <el-divider />
                  </div>
                </template>
              </div>
            </el-card>
          </el-col>
        </el-main>
      </el-container>
    </el-container>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  recordData: {
    type: Array,
    default: () => [],
    required: false,
  },
})

const emit = defineEmits(['update:visible', 'close', 'confirm'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit('update:visible', val)
  },
})

// 确保recordData始终是数组并按序号排序
const safeRecordData = computed(() => {
  console.log('ExamSummaryDialog接收到的recordData:', props.recordData)
  
  // 首先确保recordData是数组
  if (!props.recordData) {
    console.warn('recordData为空或未定义')
    return []
  }
  
  // 确保是数组类型
  if (!Array.isArray(props.recordData)) {
    console.warn('recordData不是数组类型:', typeof props.recordData)
    return []
  }
  
  // 过滤掉无效数据项
  const validData = props.recordData.filter((item) => {
    const isValid = !!item && item.id !== undefined
    if (!isValid) {
      console.warn('过滤掉无效recordData项:', item)
    }
    return isValid
  })
  
  if (validData.length === 0) {
    console.warn('过滤后的validData为空数组')
    return []
  }
  
  console.log('过滤后有效数据条数:', validData.length)
  
  // 按照题目序号排序
  try {
    return validData.sort((a, b) => {
      // 防御性编程，确保sort属性存在
      const sortA = a && a.sort !== undefined ? a.sort : 0
      const sortB = b && b.sort !== undefined ? b.sort : 0
      return sortA - sortB
    })
  } catch (error) {
    console.error('排序recordData时出错:', error)
    return validData // 如果排序出错，返回未排序的数据
  }
})

// 格式化用户答案显示
const formatUserAnswer = (item) => {
  // 防御性检查
  if (!item) {
    console.warn('formatUserAnswer: item为空')
    return '未作答'
  }
  
  // 检查答案并打印日志
  console.log(
    `格式化答案 - 题目ID:${item.id || '未知'}, 类型:${
      item.quType || '未知'
    }, 原始答案:${item.myOption || '无'}`
  )

  // 如果没有答案就返回未作答
  if (!item.myOption || item.myOption.trim() === '') {
    return '未作答'
  }

  try {
    // 对于多选题，将逗号分隔的选项转为字母
    if (item.quType === 2) {
      // 确保myOption是字符串
      const myOptionStr = String(item.myOption)
      if (!myOptionStr.includes(',') && myOptionStr.trim() === '') {
        return '未作答'
      }
      
      const letters = myOptionStr
        .split(',')
        .map((opt) => numberToLetter(opt))
        .filter(letter => letter) // 过滤掉空字母
        .join(',')
        
      console.log(`多选题答案转换: ${item.myOption} -> ${letters}`)
      return letters || '未作答'
    }

    // 对于单选题和判断题，直接转换为字母
    const letter = numberToLetter(item.myOption)
    console.log(`单选/判断题答案转换: ${item.myOption} -> ${letter}`)
    return letter || '未作答'
  } catch (error) {
    console.error('格式化答案出错:', error, 'item:', JSON.stringify(item))
    return '未作答'
  }
}

// 检查选项是否被选中
const isCheck = (myOption, sort) => {
  // 防御性检查
  if (!myOption) return false
  if (sort === undefined || sort === null) return false

  try {
    // 确保myOption是字符串
    const myOptionStr = String(myOption)
    // 将选项转为字符串
    const sortString = String(sort)
    
    console.log(`检查选项 - 答案:${myOptionStr}, 当前选项sort:${sortString}`)

    // 处理单个数字的情况
    if (!myOptionStr.includes(',')) {
      return myOptionStr === sortString
    }

    // 处理逗号分隔的情况
    const arr = myOptionStr.split(',')
      .map((option) => option.trim())
      .filter((option) => option !== '') // 过滤掉空字符串
      
    return arr.includes(sortString)
  } catch (error) {
    console.error(
      '解析答案选项出错:',
      error,
      'myOption:',
      myOption,
      'sort:',
      sort
    )
    return false
  }
}

// 处理对话框关闭
const handleClose = (done) => {
  emit('close')
  done()
}

// 取消按钮
const onCancel = () => {
  dialogVisible.value = false
}

// 确认按钮
const onConfirm = () => {
  emit('confirm')
  dialogVisible.value = false
}

// 获取答案颜色
const getAnswerColor = (isRight) => {
  if (isRight === 1) return '#67C23A'
  if (isRight === 0) return '#F56C6C'
  return '#909399'
}

// 获取答案样式类
const getAnswerClass = (isRight) => {
  if (isRight === 1) return 'correct-answer'
  if (isRight === 0) return 'wrong-answer'
  return 'neutral-answer'
}

// 将数字转换为字母
const numberToLetter = (input) => {
  if (input === null || input === undefined || input === '') return ''

  const numberToCharMap = {
    0: 'A',
    1: 'B',
    2: 'C',
    3: 'D',
    4: 'E',
    5: 'F',
  }

  try {
    // 处理单个数字
    if (typeof input === 'number' || /^\d+$/.test(input)) {
      const num = parseInt(input, 10)
      const letter = numberToCharMap[num]
      if (!letter) {
        console.warn(`无法将数字 ${num} 转换为字母, 不在映射范围内`)
      }
      return letter || ''
    }

    // 处理逗号分隔的数字
    if (typeof input === 'string' && /^\d+(,\d+)*$/.test(input)) {
      return input
        .split(',')
        .map((num) => {
          const parsedNum = parseInt(num.trim(), 10)
          const letter = numberToCharMap[parsedNum]
          if (!letter) {
            console.warn(`无法将数字 ${parsedNum} 转换为字母, 不在映射范围内`)
          }
          return letter || ''
        })
        .filter(letter => letter) // 过滤掉空字母
        .join(',')
    }

    console.warn(`无法处理的输入类型: ${typeof input}, 值: ${input}`)
    return String(input)
  } catch (error) {
    console.error('转换字母出错:', error, 'input:', input)
    return ''
  }
}
</script>

<style scoped>
.exam-summary-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.exam-summary-dialog :deep(.el-dialog__body) {
  padding: 10px 20px;
}

.qu_list {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-item {
  padding: 15px 10px;
  margin-bottom: 10px;
}

.question-title {
  margin-bottom: 15px;
  font-weight: 500;
}

.qu_content {
  line-height: 1.6;
  margin-bottom: 10px;
}

.qu_num {
  display: inline-block;
  background-color: #409eff;
  color: white;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  margin-right: 10px;
  font-weight: bold;
}

.qu_choose {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 10px 15px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.qu_choose.current {
  background-color: #f5f7fa;
  border-color: #409eff;
}

.option-letter {
  margin-right: 8px;
  font-weight: bold;
  color: #303133;
}

.option-content {
  flex: 1;
}

.qu_analysis {
  margin-top: 15px;
}

.my-answer-card {
  box-shadow: none;
  border: 1px solid #ebeef5;
}

.my-answer-card :deep(.el-card__body) {
  padding: 12px 15px;
}

.answer-label {
  font-weight: 500;
  margin-right: 10px;
}

.answer-value {
  font-weight: bold;
}

.correct-answer {
  color: #67c23a;
}

.wrong-answer {
  color: #f56c6c;
}

.neutral-answer {
  color: #909399;
}

.essay-answer {
  width: 100%;
  margin-bottom: 15px;
}

.essay-answer :deep(.el-textarea__inner) {
  border-color: #dcdfe6;
  padding: 12px 15px;
  font-size: 14px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-footer .el-button {
  min-width: 100px;
}

/* 增强样式 */
.question-item {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
}

.qu_content {
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 15px;
  line-height: 1.6;
}

.qu_num {
  font-weight: bold;
  color: #409eff;
  margin-right: 8px;
}

.option-letter {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.option-content {
  color: #303133;
}

.qu_choose {
  width: 100%;
  margin-bottom: 8px;
  padding: a10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.qu_choose:hover {
  background-color: #f0f9ff;
  border-color: #c0c4cc;
}

.current {
  background-color: #ecf5ff !important;
  border-color: #409eff !important;
  color: #409eff !important;
}

.answer-label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.answer-value {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.correct-answer {
  background-color: #f0f9eb;
  color: #67c23a;
}

.wrong-answer {
  background-color: #fef0f0;
  color: #f56c6c;
}

.neutral-answer {
  background-color: #f4f4f5;
  color: #909399;
}

.my-answer-card {
  margin-top: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.my-answer-card :deep(.el-card__body) {
  padding: 15px;
}

.right {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
}
</style>
